import { isEmpty, isNotEmpty } from './validate'

const dataTypes = new Map<string, string>([
  ['[object Null]', 'null'],
  ['[object Undefined]', 'undefined'],
  ['[object Boolean]', 'boolean'],
  ['[object Number]', 'number'],
  ['[object String]', 'string'],
  ['[object Function]', 'function'],
  ['[object Array]', 'array'],
  ['[object Date]', 'date'],
  ['[object RegExp]', 'regexp'],
  ['[object Object]', 'object'],
  ['[object Error]', 'error'],
  ['[object Promise]', 'promise']
])

/**
 * 去值前后空格
 * @param value 值
 * @return 去空格后的值
 */
export const trim = (value: string) => {
  return value.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '')
}

/**
 * 获取值的数据类型
 * 未找到对应类型则返回 unknown
 * @param value 值
 * @return 数据类型
 */
export const getDataType = (value: any) => {
  const key = Object.prototype.toString.call(value)
  return dataTypes.get(key) || 'unknown'
}

/**
 * 获取函数名
 * @param func 函数
 * @return 函数名
 */
export const getFuncName = (func: Function) => {
  return func.name
}

/**
 * 深度复制
 * @param source 源数据
 * @return 复制数据
 */
export const deepClone = (source: any) => {
  if (isEmpty(source)) {
    return source
  } else {
    const dataType = getDataType(source)
    let target: any = null
    if (dataType === 'array') {
      target = []
      for (const value of source) {
        target.push(value)
      }
    } else if (dataType === 'object') {
      target = {}
      Object.keys(source).forEach(key => {
        const value: any = source[key]
        target[key] = deepClone(value)
      })
    } else {
      target = source
    }
    return target
  }
}
